package com.hc.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.hc.util.AuthToken;
import com.hc.util.CookieUtils;
import com.hc.util.JsonUtil;
import com.hc.util.Redis;
import com.hc.util.StringUtil;

public class AuthFilter extends OncePerRequestFilter {
	private Redis redis;

	@Override
	protected void initFilterBean() throws ServletException {
		super.initFilterBean();
		ServletContext servletContext = getServletContext();
		WebApplicationContext webApplicationContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(servletContext);
		this.redis = (Redis) webApplicationContext.getBean("redis");
	}

	@Override
	protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
			throws ServletException, IOException {
		String requestUrl = req.getRequestURI();
		/*-----------------------放行登录、登出、手机号注册接口------------------*/
		if (requestUrl.equals("/")||requestUrl.indexOf("/login") >= 0) {
			chain.doFilter(req, resp);
			return;
		}
		/*-----------------------放行短信接口，同时验证是否来自合法客户端------------------*/
		if (requestUrl.indexOf("/Msg") >= 0) {
			//
			chain.doFilter(req, resp);
			return;
		}
		/*-----------------------放行视图跳转------------------*/
		if (requestUrl.indexOf("/View") >= 0) {
			String path = req.getContextPath();
			String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
			String token = CookieUtils.getCookie(req, resp, "token", false);
			if (StringUtil.isEmpty(token)) {
				resp.sendRedirect(basePath);
			}
			String adminId= AuthToken.getInfo(token, 1);
			if (StringUtil.isEmpty(adminId)) {
				resp.sendRedirect(basePath);
			}
			return;
		}
		/*-----------------------从Header中获取Token------------------*/
		// String token = req.getParameter("Access-Token");
		// 调试阶段使用getParameter，正式请用getHeader
		String token = req.getHeader("Access-Token");
		resp.setCharacterEncoding("UTF8");
		/*-----------------------从验证中获取Token是否存在------------------*/
		if (token == null || token.equals("")) {
			resp.getWriter().write(JsonUtil.toReturnJson("501", "Your operation is illegal.", null));
			return;
		}

		/*-----------------------解密Token------------------*/
		String paintoId = AuthToken.getInfo(token, 1);
		String dev = AuthToken.getInfo(token, 2);
		if (StringUtil.isEmpty(paintoId) || StringUtil.isEmpty(dev)) {
			resp.getWriter().write(JsonUtil.toReturnJson("501", "请去登录一下吧", null));
			return;
		}
		/*-----------------------从Redis中获取Token------------------*/
		String redisToken = redis.get(paintoId);
		if (StringUtil.isEmpty(redisToken)) {
			resp.getWriter().write(JsonUtil.toReturnJson("501", "你太久没登录了，去登录一下吧", null));
			return;
		}
		/*-----------------------从解密redis中的Token获取设备Id------------------*/
		String redisDev = AuthToken.getInfo(redisToken, 2);

		/*-----------------------检查redis中的Token是否正确------------------*/
		if (StringUtil.isEmpty(redisDev)) {
			resp.getWriter().write(JsonUtil.toReturnJson("501", "请重新去登录", null));
			return;
		}

		/*-----------------------对比本次登录是否为同一设备------------------*/
		if (!redisDev.equals(dev)) {
			resp.getWriter().write(JsonUtil.toReturnJson("501", "你的账号在别处登陆了，如果不是本人操作请前去修改密码。", null));
			return;
		}
		chain.doFilter(req, resp);
		return;
	}

}
